/* Copyright (C) 2010 MoSync AB

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License, version 2, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with this program; see the file COPYING.  If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/

#include "Convert.h"
#include <mavsprintf.h>
#include "../std.h"

Convert::Convert()
{}

Convert::~Convert()
{}

int Convert::toInt(const char* digit)
{
   int sign = 1;
   int result = 0;

   // check sign
   if (*digit == '-')
   {
	  sign = -1;
	  digit++;
   }

   //--- get integer portion
   while (*digit >= '0' && *digit <='9')
   {
	  result = (result * 10) + *digit-'0';
	  digit++;
   }

   //--- set to sign given at the front
   return result * sign;
}

int Convert::toInt(String& input)
{
	return toInt(input.c_str());
}

double Convert::toDouble(String& input)
{
   int sign = 1;
   double result = 0;
   const char* digit = input.c_str();

   // check sign
   if (*digit == '-')
   {
	  sign = -1;
	  digit++;
   }

   //--- get integer portion
   while (*digit >= '0' && *digit <='9')
   {
	  result = (result * 10) + *digit-'0';
	  digit++;
   }

   //--- get decimal point and fraction, if any.
   if (*digit == '.')
   {
	  digit++;
	  double scale = 0.1;
	  while (*digit >= '0' && *digit <='9') {
		 result += (*digit-'0') * scale;
		 scale *= 0.1;
		 digit++;
	  }
   }

   //--- error if we're not at the end of the number
   if (*digit != 0) {
	  return 0.00;
   }

   //--- set to sign given at the front
   return result * sign;
}

time_t Convert::toDateTime(String& input)
{
	return (time_t)toInt(input);
}

String Convert::toString(int input)
{
	char buffer[128];
	sprintf(buffer, "%d", input);

	return buffer;
}

String Convert::toString(double input)
{
	char buffer[128];
	sprintf(buffer, "%f", input);

	return buffer;
}

int Convert::hexToInt(const char* input)
{

	int v = 0;
	while (char c = *input++)
	{
		if (c < '0') return 0; //invalid character
		if (c > '9') //shift alphabetic characters down
		{
		if (c >= 'a') c -= 'a' - 'A'; //upper-case 'a' or higher
		if (c > 'Z') return 0; //invalid character
		if (c > '9') c -= 'A'-1-'9'; //make consecutive with digits
		if (c < '9' + 1) return 0; //invalid character
		}
		c -= '0'; //convert char to hex digit value
		v = v << 4; //shift left by a hex digit
		v += c; //add the current digit
	}

	return v;
}
